<?php
namespace app\api\controller;
use think\Db;
class Publish extends Common {
	private $token;
	private $userinfo;
	
	private $ak = 'xnZHVFG7IwuFQMgHkcbIGFDx07MZnQl8';
	private $db = null;
	private $config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $orderField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
	}
	
	public function loading(){
		if (!request()->isPost()) return;
		$user_id = $this->request->post('user_id');
		$value = db('system')->where(array('name' => 'delivery_user_config'))->find();
		$value = unserialize($value['value']);
		if (empty($value)) return;
		$go_distance_time2 = $value[0]['go_distance_time2'];
		
		$prefix = config('database.prefix');
		$data = db()->query("select uc.*,u.endtime from {$prefix}coupon_use uc inner join {$prefix}coupon u ON uc.coupon_id=u.id where uc.status = 0 and uc.uid={$user_id} order by uc.time desc");
		$tmep = array();
		foreach ($data as $key => $value){
			if (time() < $value['endtime']){
				$tmep[] = $value;
			}
		}
		ajaxReturn(array('status' => 1,'data' => $tmep,'go_distance_time2' => date('Y-m-d H:i',time()+$go_distance_time2*60),'user_id' => $user_id));
	}
	
	public function commentLoading(){
		if (!request()->isPost()) return;
		$user_id = $this->request->post('user_id');
		$order_id = $this->request->post('order_id');
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $user_id))->find();
		ajaxReturn($user);
	}
	
	public function sendComment(){
		if (!request()->isPost()) return;
		$data = $this->request->post();
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $data['user_id']))->find();
		if (!empty($user)){
			$commentData = array(
				'star_num' => $data['star_num'],
				'comment' => $data['remark'],
				'ishidden' => isset($data['hidden']) ? intval($data['hidden']) : 0,
			);
			if (db('delivery_order')->where(array('user_send' => 1,'orderId' => $data['order_id']))->update($commentData)){
				ajaxReturn(array('status' => 1,'msg' => '评价成功'));	
			}
		}
		ajaxReturn(array('status' => 0,'msg' => '评价失败'));
	}
	
	/**
	 * @desc 根据两点间的经纬度计算距离
	 * @param float $lat 纬度值
	 * @param float $lng 经度值
	 */
	private function getDistance($lat1, $lng1, $lat2, $lng2){
		$earthRadius = 6367000;
		$lat1 = ($lat1 * pi() ) / 180;
		$lng1 = ($lng1 * pi() ) / 180;
		
		$lat2 = ($lat2 * pi() ) / 180;
		$lng2 = ($lng2 * pi() ) / 180;
		$calcLongitude = $lng2 - $lng1;
		$calcLatitude = $lat2 - $lat1;
		$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
		$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
		$calculatedDistance = $earthRadius * $stepTwo;
		return round($calculatedDistance / 1000,2);
		//return round($calculatedDistance * 10000) / 10000;
	}
	
	public function count(){
		if (!request()->isPost()) ajaxReturn(array('status' => 1,'totalMoney' => '0.00'));
//		file_put_contents('count_dis.txt',var_export($_REQUEST,true));
// 		exit;
		$user_id = $this->request->post('user_id');
		$type = $this->request->post('type');
		$buy_lng = $this->request->post('buy_lng'); //经度
		$buy_lat = $this->request->post('buy_lat'); //纬度
		
		$go_lng = $this->request->post('go_lng');
		$go_lat = $this->request->post('go_lat');
		
		$get_lng = $this->request->post('get_lng');
		$get_lat = $this->request->post('get_lat');
		
		if (empty($get_lat) || empty($get_lng)){
			ajaxReturn(array('status' => 1,'totalMoney' => '0.00'));
		}
		
		$car = $this->request->post('car');
		$urgent = $this->request->post('urgent');
		$coupon = $this->request->post('coupon');
		// 默认只有 1 帮我送
		if ($type == 3){
			$getDistance = $this->getDistance($buy_lat, $buy_lng, $get_lat, $get_lng);
		}else{
			$getDistance = $this->getDistance($go_lat, $go_lng, $get_lat, $get_lng);
		}
		
		/**
		    <option value="1">帮我送</option>
		    <option value="2">帮我取</option>
		    <option value="3">帮我买</option>
		    <option value="1">摩托车(电动车)</option>
		    <option value="2">小汽车</option>
		    <option value="3">火车</option>
		 */
		$this->user_id = $user_id;
		$totalMoney = $this->totalMoney($car, $urgent, $coupon, $getDistance);
		
		ajaxReturn(array('status' => 1,'totalMoney' => $totalMoney,'getDistance' => $getDistance));
		
	}
	
	private function totalMoney($car,$urgent,$coupon,$getDistance){
		$totalMoney = 0;
		$value = db('system')->where(array('name' => 'delivery_user_config'))->find();
		$value = unserialize($value['value']);

		if (empty($value)) return;
		$temp = array();
		foreach ($value as $k => $v){
			if ($v['go_distance'] >= $getDistance){
				$temp = $v;
				break;
			}
		}
		if (!empty($temp)) {
			switch ($car){
				case 1:
					$count_free = $temp['go_money'];
					break;
				// case 2:
				// 	$count_free = $temp['go_money2'];
				// 	break;
				// case 3:
				// 	$count_free = $temp['go_money3'];
				// 	break;
			}
		}else{
			// $count_free = 10; //超过距离，封顶计费
			ajaxReturn(array('status' => -2,'totalMoney' => '配送距离不在平台设置范围','getDistance' => $getDistance));
		}
		$totalMoney = $count_free;
		//加急配送
		// if ($urgent == 2){
		// 	$user_urgent = db('system')->where(array('name' => 'user_urgent'))->find();
		// 	$user_urgent =  (float)$user_urgent['value']/100;
		// 	$totalMoney = $totalMoney + $totalMoney*$user_urgent;
		// }
		
		// if ($coupon){
		// 	$coupon_data = db('coupon_use')->where(array('uid' => $this->user_id,'id' => $coupon,'status' => 0))->find();
		// 	if (!empty($coupon_data)){
		// 		$totalMoney = $totalMoney-$coupon_data['money'];
		// 		if ($totalMoney <= 0) $totalMoney = 0;
		// 	}
		// }
		return subMoney($totalMoney);
	}

	// 唐峰康改 发布跑腿任务余额支付 验证
	public function balancePay(){
		if (!request()->isPost()) ajaxReturn(array('status' => -1,'msg' => '请求错误，请重试'));
		$data = $this->request->post();
		$user_id = $data['user_id'];
		$order_id = $data['order_id'];
		$pwd = $data['pwd'];
		// 订单信息
		$send_order_info = db('send_order')->where(array('id'=>$order_id))->find();
		$needPay = $send_order_info['money']+$send_order_info['extra_money'];
		// ajaxReturn(array('status' => 1,'msg' => '支付成功,提交成功','data'=>$send_order_info));

		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $user_id))->find();

		$pwd=md5($pwd.$user['loginSecret']);
		if ($pwd == $user['payPwd']) {

			if ($send_order_info['pay_status'] == 1) {
				ajaxReturn(array('status' => -2,'msg' => '订单已支付！'));
			}
			$A = $db->name('users')->where(array('userId' => $user_id))->setDec('userMoney',$needPay);
			if ($A!==false) {
				// 生成支付记录
				$db_config = config('database.db_config');
				$db = \Think\Db::connect($db_config);
				$recordData = array();
				// 跑腿单
				$recordData['type'] = 6;
				$recordData['money'] = $needPay;
				$recordData['time'] = time();
				$recordData['orderNo'] = $order_id;
				$recordData['IncDec'] = 0;
				$recordData['userid'] = $user_id;
				$recordData['remark'] = '消费';
				$recordData['balance'] = $user['userMoney'] - $needPay;
				// 余额支付
				$recordData['payWay'] = 3;
				$db->name('money_record')->insert($recordData);

				// 修改订单状态
				$B = db('send_order')->where(array('id' => $order_id))->setField('pay_status',1);

				ajaxReturn(array('status' => 1,'msg' => '支付成功,提交成功','A'=>$A,'B'=>$B));
			}

		}else{
			ajaxReturn(array('status' => -1,'msg' => '支付密码错误!'));
		}
	}


	// 唐峰康 判断是不是夜间配送
	public function isNight(){
		$time = date('H:i:s',time());
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$starTime =$db->name('sys_configs')->where(array('fieldCode'=>'starTime'))->value('fieldValue');
		$endTime = $db->name('sys_configs')->where(array('fieldCode'=>'endTime'))->value('fieldValue');
		$nightRatio =  $db->name('sys_configs')->where(array('fieldCode'=>'nightRatio'))->value('fieldValue');
		$extraDeliveryMoney =  $db->name('sys_configs')->where(array('fieldCode'=>'extraDeliveryMoney'))->value('fieldValue');
		$data =array();
		$data['nightRatio'] = $nightRatio;
		$data['extraDeliveryMoney'] = $extraDeliveryMoney;

		// 默认是在一天内的
		if ($time >=$starTime && $time<=$endTime) {
			$data['isNight'] = 1;
		}else{
			$data['isNight'] = -1;
		}

		$data['time'] = $time;

		// 如果是跨过1天 结束时间小于开始时间为跨一天
		if ($endTime < $starTime) {

			$data['endTime'] = $endTime;
			$data['starTime'] = $starTime;
			// ajaxReturn($data);

			// 在当天内
			if ($time <= '24:00:00' && $time >= $starTime) {
				$data['isNight'] = 1;
				$data['time'] = $time;
			}else if ($time >= '00:00:00' && $time <= $endTime) {
				$data['isNight'] = 1;
				$data['time'] = $time;
			}else{
				$data['isNight'] = -1;
			}
			
		}	

		// 只有一个时间点的时候
		if ($endTime == $starTime && $starTime == $time) {
			$data['isNight'] = 1;
		}
		// dump($data);
		ajaxReturn($data);
	}



		// 唐峰康 判断是不是夜间配送 测试 使用
	public function isNight2(){
		// $time = date('H:i:s',time());

		$time = "00:30:30";
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$starTime =$db->name('sys_configs')->where(array('fieldCode'=>'starTime'))->value('fieldValue');
		$endTime = $db->name('sys_configs')->where(array('fieldCode'=>'endTime'))->value('fieldValue');
		$nightRatio =  $db->name('sys_configs')->where(array('fieldCode'=>'nightRatio'))->value('fieldValue');
		$extraDeliveryMoney =  $db->name('sys_configs')->where(array('fieldCode'=>'extraDeliveryMoney'))->value('fieldValue');
		$data =array();
		$data['nightRatio'] = $nightRatio;
		$data['extraDeliveryMoney'] = $extraDeliveryMoney;
		if ($time >=$starTime && $time<=$endTime) {
			$data['isNight'] = 1;
		}else{
			$data['isNight'] = -1;
		}

		// 如果是跨过1天 结束时间小于开始时间为跨一天
		if ($endTime < $starTime) {

			$data['endTime'] = $endTime;
			$data['starTime'] = $starTime;
			// ajaxReturn($data);

			// 在当天内
			if ($time <= '24:00:00' && $time >= $starTime) {
				$data['isNight'] = 1;
				$data['time'] = $time;
			}else if ($time >= '00:00:00' && $time <= $endTime) {
				$data['isNight'] = 1;
				$data['time'] = $time;
			}else{
				$data['isNight'] = -1;
			}
			
		}
		// dump($data);
		ajaxReturn($data);
	}

	// 唐峰康改 提交发布跑腿任务订单 需要跳转支付方式选择页面
	public function send(){

		//file_put_contents('send.txt', var_export($_POST,true));
		/**
		 <option value="1">帮我送</option>
		 <option value="2">帮我取</option>
		 <option value="3">帮我买</option>
		 <option value="1">摩托车(电动车)</option>
		 <option value="2">小汽车</option>
		 <option value="3">火车</option>
		 */
		// if (!request()->isPost()) ajaxReturn(array('status' => 1,'totalMoney' => '0.00'));//hide 7.9
		if (!request()->isPost()) ajaxReturn(array('status' => 0,'totalMoney' => '0.00'));
		// ajaxReturn(array('status' => 1,'msg' => '2131'));
		$data = $this->request->post();
		// ajaxReturn(array('status' => 1,'msg' => json_encode($data)));
		$user_id = $data['user_id'];

		/** add 7.9 */
		$userInfo = $this->db->name('users')->where(array('userId' => $user_id,'userStatus'=>1,'userFlag'=>1,'isAudit'=>1))->find();
		if(empty($userInfo)){
			ajaxReturn(array('status'=>0,'msg'=>'需要通过审核才能进行发布订单'));
		}
		/** add end */

		$type = $data['type'];
		// $buy_lng = $data['buy_lng'];//经度
		// $buy_lat = $data['buy_lat'];//纬度
		$go_lng = $data['go_lng'];
		$go_lat = $data['go_lat'];
		$get_lng = $data['get_lng'];
		$get_lat = $data['get_lat'];
		// ajaxReturn(array('status' => 1,'msg' =>'wasdas'));
		if (empty($get_lat) || empty($get_lng)){
			ajaxReturn(array('status' => 0,'totalMoney' => '0.00'));
		}
		if ($type == 1 || $type == 4){
			$getDistance = $this->getDistance($go_lat, $go_lng, $get_lat, $get_lng);
			$user_lng = $go_lng;
			$user_lat = $go_lat;
		}else{
			// $getDistance = $this->getDistance($buy_lat, $buy_lng, $get_lat, $get_lng);
			// $user_lng = $buy_lng;
			// $user_lat = $buy_lat;
		}
		// ajaxReturn(array('status' => 1,'msg' =>$getDistance));
		$this->user_id = $user_id;
		$totalMoney = $this->totalMoney($data['car'], $data['urgent'], $data['coupon'], $getDistance);
		$send_order_num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
		$insertData = array(
			'type' => $type,
			'send_order_num' => $send_order_num,
			'uid' => $user_id,
			'delivery_uid' => 0,
			'pay_type' => $data['pay_type'],
			'proportion' => $data['nightRatio'],
			'extra_money' => $data['extraDeliveryMoney'],
			'money' => $totalMoney,
			'order_status' => 0,
			'content' => json_encode($data),
			'user_lng' => $user_lng,
			'user_lat' => $user_lat,
			'send_time' => strtotime($data['send_time']),
			'time' => time()
		);

		if($type==4){
			$insertData['elemId'] = $data['elemId']; 
		}

		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $user_id))->find();
		$insertData['username'] = $user['userPhone'];
		$orderId = db('send_order')->insertGetId($insertData);
		$totalMoney = $totalMoney + $data['extraDeliveryMoney'];
		if ($orderId){
			ajaxReturn(array('status' => 1,'msg' => '订单提交成功','send_order_id'=>$orderId,'pay_type'=>$data['pay_type'],'totalMoney'=>$totalMoney));
		}else{
			ajaxReturn(array('status' => 0,'msg' => '提交失败'));
		}

		// if ($data['pay_type'] == 0){
		// 	$db_config = config('database.db_config');
		// 	$db = \Think\Db::connect($db_config);
		// 	$user = $db->name('users')->where(array('userId' => $user_id))->find();
		// 	$insertData['username'] = $user['userPhone'];
		// 	$orderId = db('send_order')->insert($insertData);
		// 	if ($orderId){
		// 		ajaxReturn(array('status' => 1,'msg' => '订单提交成功','send_order_id'=>$orderId));
		// 	}
		// 	if ($db->name('users')->where(array('userId' => $user_id))->setDec('userMoney',$totalMoney)){
		// 		$insertData['pay_status'] = 1;
		// 		$insertData['username'] = $user['userPhone'];
		// 		$orderId = db('send_order')->insert($insertData);
		// 		if ($orderId){
		// 			// 生成支付记录
		// 			$db_config = config('database.db_config');
		// 			$db = \Think\Db::connect($db_config);
		// 			$recordData = array();
		// 			// 跑腿单
		// 			$recordData['type'] = 6;
		// 			$recordData['money'] = $totalMoney;
		// 			$recordData['time'] = time();
		// 			$recordData['orderNo'] = $orderId;
		// 			$recordData['IncDec'] = 0;
		// 			$recordData['userid'] = $user_id;
		// 			$recordData['remark'] = '消费';
		// 			$recordData['balance'] = $user['userMoney'] - $totalMoney;
		// 			// 余额支付
		// 			$recordData['payWay'] = 3;
		// 			$db->name('money_record')->insert($recordData);
		// 			// 没有优惠券-唐改
		// 			// db('coupon_use')->where(array('uid' => $user_id,'id' => $data['coupon']))->setField('status',1);
		// 			ajaxReturn(array('status' => 1,'msg' => '支付成功,提交成功'));
		// 		}else{
		// 			$db->name('users')->where(array('userId' => $user_id))->setInc('userMoney',$totalMoney);
		// 			ajaxReturn(array('status' => 0,'msg' => '提交失败'));
		// 		}
		// 	}else{
		// 		ajaxReturn(array('status' => 0,'msg' => '支付失败,请稍候...'));
		// 	}
		// }else{
		// 	ajaxReturn(array('status' => 0,'msg' => '微信支付宝开发中...'));
		// }		
	}
	
	//发布帮我跑腿->之前 不使用支付密码的版本
	public function send2(){

		//file_put_contents('send.txt', var_export($_POST,true));
		/**
		 <option value="1">帮我送</option>
		 <option value="2">帮我取</option>
		 <option value="3">帮我买</option>
		 <option value="1">摩托车(电动车)</option>
		 <option value="2">小汽车</option>
		 <option value="3">火车</option>
		 */
		if (!request()->isPost()) ajaxReturn(array('status' => 1,'totalMoney' => '0.00'));
		// ajaxReturn(array('status' => 1,'msg' => '2131'));
		$data = $this->request->post();
		// ajaxReturn(array('status' => 1,'msg' => json_encode($data)));
		$user_id = $data['user_id'];
		$type = $data['type'];
		// $buy_lng = $data['buy_lng'];//经度
		// $buy_lat = $data['buy_lat'];//纬度
		$go_lng = $data['go_lng'];
		$go_lat = $data['go_lat'];
		$get_lng = $data['get_lng'];
		$get_lat = $data['get_lat'];
		// ajaxReturn(array('status' => 1,'msg' =>'wasdas'));
		if (empty($get_lat) || empty($get_lng)){
			ajaxReturn(array('status' => 0,'totalMoney' => '0.00'));
		}
		if ($type == 1){
			$getDistance = $this->getDistance($go_lat, $go_lng, $get_lat, $get_lng);
			$user_lng = $go_lng;
			$user_lat = $go_lat;
		}else{
			// $getDistance = $this->getDistance($buy_lat, $buy_lng, $get_lat, $get_lng);
			// $user_lng = $buy_lng;
			// $user_lat = $buy_lat;
		}
		$this->user_id = $user_id;
		$totalMoney = $this->totalMoney($data['car'], $data['urgent'], $data['coupon'], $getDistance);
		$insertData = array(
			'type' => $type,
			'uid' => $user_id,
			'delivery_uid' => 0,
			'pay_type' => $data['pay_type'],
			'money' => $totalMoney,
			'order_status' => 0,
			'content' => json_encode($data),
			'user_lng' => $user_lng,
			'user_lat' => $user_lat,
			'send_time' => strtotime($data['send_time']),
			'time' => time()
		);
		if ($data['pay_type'] == 0){
			$db_config = config('database.db_config');
			$db = \Think\Db::connect($db_config);
			$user = $db->name('users')->where(array('userId' => $user_id))->find();
			if ($db->name('users')->where(array('userId' => $user_id))->setDec('userMoney',$totalMoney)){
				$insertData['pay_status'] = 1;
				$insertData['username'] = $user['userPhone'];
				$orderId = db('send_order')->insert($insertData);
				if ($orderId){
					// 生成支付记录
					$db_config = config('database.db_config');
					$db = \Think\Db::connect($db_config);
					$recordData = array();
					// 跑腿单
					$recordData['type'] = 6;
					$recordData['money'] = $totalMoney;
					$recordData['time'] = time();
					$recordData['orderNo'] = $orderId;
					$recordData['IncDec'] = 0;
					$recordData['userid'] = $user_id;
					$recordData['remark'] = '消费';
					$recordData['balance'] = $user['userMoney'] - $totalMoney;
					// 余额支付
					$recordData['payWay'] = 3;
					$db->name('money_record')->insert($recordData);
					// 没有优惠券-唐改
					// db('coupon_use')->where(array('uid' => $user_id,'id' => $data['coupon']))->setField('status',1);
					ajaxReturn(array('status' => 1,'msg' => '支付成功,提交成功'));
				}else{
					$db->name('users')->where(array('userId' => $user_id))->setInc('userMoney',$totalMoney);
					ajaxReturn(array('status' => 0,'msg' => '提交失败'));
				}
			}else{
				ajaxReturn(array('status' => 0,'msg' => '支付失败,请稍候...'));
			}
		}else{
			ajaxReturn(array('status' => 0,'msg' => '微信支付宝开发中...'));
		}		
	}
	
	public function lists(){
		if (!request()->isPost()) ajaxReturn(array('status' => 0));
		$postData = $this->request->post();
		if (empty($postData)) ajaxReturn(array('status' => 0));
		$orderStatus = intval($postData['status']);
		
		if ($orderStatus){
			// 唐峰康修改  未接单的状态只获取0 的状态， 配送中包括状态1 已接单，未取货的 配送员未确认到达的
			if ($orderStatus == 2 ) {
				$where = " uid='{$postData['user_id']}' and pay_status =1 and is_delivery_confirm = -1 and (order_status='{$orderStatus}' OR order_status=1)";
			}
			//已到达状态 获取配送员已经确认到达的 订单为配送中且 配送员已经配送到达
			else if ($orderStatus == 6) {

				$where = " order_status=2 and pay_status = 1 and is_delivery_confirm = 1 and uid='{$postData['user_id']}'";
			}
			// 取消/已完成
			else{
			
				$where = " uid = '{$postData['user_id']}' and order_status='{$orderStatus}' and pay_status >=1";

			}
			// $where = " uid='{$postData['user_id']}' and (order_status='{$orderStatus}' OR order_status=1)";
		}else{
			// $where = "(order_status=1 OR order_status=0) and uid='{$postData['user_id']}'";
			$where = " order_status=0 and pay_status = 1 and uid='{$postData['user_id']}'";
		}
	
		$lists = db('send_order')->where($where)->select();
		
		foreach ($lists as $key => $value){
			$content = json_decode($value['content'],true);
			switch ($content['car']){
				case 1:
					$content['car_text'] = '摩托车(电动车)';
					break;
				case 2:
					$content['car_text'] = '小汽车';
					break;
				case 3:
					$content['car_text'] = '火车';
					break;
			}
			switch ($content['type']){
				case 1:
					$content['type_text'] = '帮我送';
					break;
				case 2:
					$content['type_text'] = '帮我取';
					break;
				case 3:
					$content['type_text'] = '帮我买';
					break;
			}
			$lists[$key]['content'] = $content;
		}
		ajaxReturn(array('status' => 1,'data' => $lists));
	}
	
	public function desc(){
		//header('Access-Control-Allow-Origin:*');//任何
		if (!request()->isPost()) ajaxReturn(array('status' => 0));
		$postData = $this->request->post();
		if (empty($postData)) ajaxReturn(array('status' => 0));
		$data = db('send_order')->where(array('uid' => $postData['user_id'],'id' => $postData['id']))->find();
		if (!empty($data)){
			$data['content'] = json_decode($data['content'],true);
			switch ($data['content']['car']){
				case 1:
					$data['content']['car_text'] = '摩托车(电动车)';
					break;
				case 2:
					$data['content']['car_text'] = '小汽车';
					break;
				case 3:
					$data['content']['car_text'] = '火车';
					break;
			}
			switch ($data['content']['type']){
				case 1:
					$data['content']['type_text'] = '帮我送';
					break;
				case 2:
					$data['content']['type_text'] = '帮我取';
					break;
				case 3:
					$data['content']['type_text'] = '帮我买';
					break;
			}

			/** add by hfc 5.15  */
			// $lngAndLat = $this->doGet($data['content']['get_lat'],$data['content']['get_lng']);
			// $data['content']['get_lng'] = $lngAndLat['lng'];
			// $data['content']['get_lat'] = $lngAndLat['lat'];
			// $lngAndLat = $this->doGet($data['content']['go_lat'],$data['content']['go_lng']);
			// $data['content']['go_lng'] = $lngAndLat['lng'];
			// $data['content']['go_lat'] = $lngAndLat['lat'];
			/** add end */
			
			$delivery_order = db('delivery_order')->where(array('orderId' => $data['id'],'user_send' => 1))->find();
			$delivery_position_info = explode(',', $delivery_order['diliverymanLngLat']);
			if (!empty($delivery_order)){
				$user = db('user')->where(array('id' => $delivery_order['userId']))->find();
				$data['delivery_username'] = $user['truename'];
				$data['delivery_phone'] = $user['mobile'];
				$data['star_num'] = $delivery_order['star_num'];
				$data['diliveryman_lng'] = $delivery_position_info[0];
				$data['diliveryman_lat'] = $delivery_position_info[1];

				/** add by hfc 5.15  */
				// $lngAndLat = $this->doGet($delivery_position_info[1],$delivery_position_info[0]);
				// $data['diliveryman_lng'] = $lngAndLat['lng'];
				// $data['diliveryman_lat'] = $lngAndLat['lat'];
				/** add end */

				$center_lng = ($data['diliveryman_lng'] + $data['content']['get_lng']+$data['content']['go_lng'])/3;
				$center_lat = ($data['diliveryman_lat'] + $data['content']['get_lat']+$data['content']['go_lat'])/3;
				$data['center_lng'] = round($center_lng,6);
				$data['center_lat'] = round($center_lat,6);
			}else{
				$data['delivery_username'] = '';
				$data['delivery_phone'] = '';
				$data['star_num'] = 0;
				$data['diliveryman_lng'] = '';
				$data['diliveryman_lat'] = '';
			}
			$data['send_time'] = date('Y-m-d H:i:s',$data['send_time']);
		}
		ajaxReturn(array('status' => 1,'data' => $data));
	}
	
	public function handlerstatus(){
		if (!request()->isPost()) ajaxReturn(array('status' => 0));
		$postData = $this->request->post();
		$type = $postData['type'];
		if (empty($postData)) ajaxReturn(array('status' => 0));
		$data = db('send_order')->where(array('uid' => $postData['user_id'],'id' => $postData['id']))->find();
		$delivery_order = db('delivery_order')->where(array('orderId' => $data['id'],'user_send' => 1))->find();
		$total_pay_money = $data['money'] + $data['extra_money'];
		if (!empty($data) && !empty($delivery_order)){
			if ($type == 'cancel'){
				// 订单状态，如果为1 则扣除用户部分金额(后台【退单设置】)配送员不得分成 2则不退给客户，配送员得分成
				$send_order_status = $data['order_status'];
				$backMoney = floatval($total_pay_money);
				if ($send_order_status == 1) {
					$userCancelSet = db('system')->where(array('id'=> 32))->find();
					$deductScale = $userCancelSet['value'];
					$scaleArray = explode('%', $deductScale);
					$scale = floatval($scaleArray[0])/100.00;
					$backMoney = $backMoney * (1 - $scale);
				}else if ($send_order_status == 2){
					$backMoney = 0;
					// 配送员会得到分成->直接加到到钱包
					// $delivery_uid = $data['delivery_uid'];
					// db('user')
				}
				$A = db('send_order')->where(array('id' => $data['id']))->setField('order_status',5);
				$B = db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array(
						'cancel_time' => time(),'iscancel' => 1));
				$C = db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array(
						'cancel_time' => time()));
			
				if ($A !== false && $B !== false && $C !== false) {
					
					$db_config = config('database.db_config');
					$db = \Think\Db::connect($db_config);
					$user = $db->name('users')->where(array('userId' => $data['uid']))->find();
					$db->name('users')->where(array('userId' => $data['uid']))->setInc('userMoney',$backMoney);
					// 余额变动记录
					$recordData = array();
					// 跑腿单
					$recordData['type'] = 2;
					$recordData['money'] = $backMoney;
					$recordData['time'] = time();
					$recordData['orderNo'] = $data['id'];
					$recordData['IncDec'] = 1;
					$recordData['userid'] = $data['uid'];
					$recordData['remark'] = '取消订单';
					$recordData['balance'] = $user['userMoney'] + $backMoney;
					// 余额支付
					$recordData['payWay'] = 3;
					$db->name('money_record')->insert($recordData);

				}

			}elseif ($type == 'refund'){
				db('send_order')->where(array('id' => $data['id']))->setField('pay_status',2);
				//不需要配送员退款
				db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array(
						'cancel_time' => time(),'iscancel' => 1
				));
			}elseif ($type == 'confirm'){
				// 唐峰康改
				// 以用户确认到达为准  只要用户确认到达 则不需要配送员确认
				db('send_order')->where(array('id' => $data['id']))->update(array('order_status' => 3,'is_user_confirm' => 1,'is_delivery_confirm' => 1));
				db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array('status' => 3,'confirm_time' => time()));
				// 判断有没有送达时间 配送员确认了有送达时间，就不覆盖
				if ($delivery_order['send_to_time'] == 0) {
					db('delivery_order')->where(array('id' => $delivery_order['id']))->setField('send_to_time',time());
				}

				// 之前的
				// db('send_order')->where(array('id' => $data['id']))->setField('order_status',3);
				// db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array('status' => 3,'confirm_time' => time(),'send_to_time' => time()));
			}
			ajaxReturn(array('status' => 1,'msg' => '操作成功'));
		}
		// 未接单 send_order 订单为0的 ，直接退全部余额 订单金额+夜间配送金额 一样退回
		elseif (!empty($data)){
			if ($type == 'cancel'){
				if (db('send_order')->where(array('id' => $data['id']))->setField('order_status',5) && $data['pay_status'] == 1){
					$db_config = config('database.db_config');
					$db = \Think\Db::connect($db_config);
					$user = $db->name('users')->where(array('userId' => $data['uid']))->find();
					if ($db->name('users')->where(array('userId' => $data['uid']))->setInc('userMoney',$total_pay_money)){
					
					// 余额变动记录
					$recordData = array();
					// 跑腿单
					$recordData['type'] = 2;
					$recordData['money'] = $total_pay_money;
					$recordData['time'] = time();
					$recordData['orderNo'] = $data['id'];
					$recordData['IncDec'] = 1;
					$recordData['userid'] = $data['uid'];
					$recordData['remark'] = '取消订单';
					$recordData['balance'] = $user['userMoney'] + $total_pay_money;
					// 余额支付
					$recordData['payWay'] = 3;
					$db->name('money_record')->insert($recordData);

					ajaxReturn(array('status' => 1,'msg' => '费用已退回余额中'));
					}
				}else{
					ajaxReturn(array('status' => 0));
				}
			}
		}else{
			ajaxReturn(array('status' => 0));
		}
	}
	
	/**
	 *   <option value="0">选择退款原因</option>
            <option value="1">多拍/错拍/不想要</option>
            <option value="2">服务承诺</option>
            <option value="3">商品少件/破损/污渍等</option>
            <option value="4">功能未达到标准效果</option>
            <option value="5">质量问题</option>
            <option value="6">功能缺失</option>
            <option value="7">假冒品牌</option>
            <option value="8">外观/型号/参数描述不符</option>
            <option value="9">卖家发错货</option>
            <option value="10">其他</option>
	 */
	
	public function send_refund(){
		if (!request()->isPost()) ajaxReturn(array('status' => 0));
		$postData = $this->request->post();
		if (empty($postData)) ajaxReturn(array('status' => 0));
		$data = db('send_order')->where(array('pay_status' => 1,'uid' => $postData['user_id'],'id' => $postData['id']))->find();
		// $data = db('send_order')->where(array('pay_status' => 1,'pay_type' => array('NEQ',0),'uid' => $postData['user_id'],'id' => $postData['id']))->find();
		$delivery_order = db('delivery_order')->where(array('orderId' => $data['id'],'user_send' => 1))->find();
		// ajaxReturn(array('status' => 0,'msg' => '申请失败','data'=>$data,'delivery_order'=>$delivery_order,'postData'=>$postData));
		if (!empty($data) && !empty($delivery_order)){
			if (db('send_order')->where(array('id' => $data['id']))->update(array('pay_status' => 2,'order_status' => 5))){
				db('delivery_order')->where(array('id' => $delivery_order['id']))->update(array(
					'refund_type' => $postData['refund'],
					'refund_desc' => $postData['remark'],
					'cancel_time' => time(),
					'iscancel' => 1,
				));
				ajaxReturn(array('status' => 1,'msg' => '申请退款成功'));
			}
		}
		ajaxReturn(array('status' => 0,'msg' => '申请失败'));
	}

	// 唐峰康改  第三方支付同步回调订单处理
	public function thirdPayment(){
		if (!request()->isPost()) ajaxReturn(array('status' => -1,'msg' => '请求错误，请重试'));
		$data = $this->request->post();
		$user_id = $data['user_id'];
		$order_id = $data['order_id'];
		$payWay = $data['pay_way'];

		// 获取用户信息
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $user_id))->find();

		// 订单信息
		$send_order_info = db('send_order')->where(array('id'=>$order_id))->find();
		// 同步回调如果 异步支付已经修改状态直接返回支付成功 只有是未支付状态 才继续
		if ($send_order_info['pay_status'] != 0) {
			ajaxReturn(array('status' => 1,'msg' => '支付成功！'));
		}

		// 生成支付记录
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$recordData = array();
		// 跑腿单
		$recordData['type'] = 6;
		$recordData['money'] = $send_order_info['money'];
		$recordData['time'] = time();
		$recordData['orderNo'] = $order_id;
		$recordData['IncDec'] = 0;
		$recordData['userid'] = $user_id;
		$recordData['remark'] = '消费';
		$recordData['balance'] = $user['userMoney'];
		// 支付方式
		$recordData['payWay'] = $payWay;
		$db->name('money_record')->insert($recordData);

		// 修改订单状态
		$rs = db('send_order')->where(array('id' => $order_id))->setField('pay_status',1);
		if ($rs !==false) {
			ajaxReturn(array('status' => 1,'msg' => '支付成功','A'=>$rs));
		}else{
			ajaxReturn(array('status' => -1,'msg' => '订单状态修改失败，请联系客服处理','A'=>$rs));
		}

				
			
	}
	//微信支付回调
	pubLic function wechatPayNotify(){
		file_put_contents('wechatpayhuidiao.txt',json_encode($this->request->post()).PHP_EOL,FILE_APPEND);
	}

	//支付宝支付回调
    public  function aliPayNotify(){
    	$response= $this->request->post();
        file_put_contents('zhifubaohuidiao.txt',json_encode($this->request->post()).PHP_EOL,FILE_APPEND);
        if ($response['trade_status'] == 'TRADE_SUCCESS'){
        	$body = $response['body'];
        	$bodyInfo = explode(',',$body);
        	// 需求定单
        	if ($bodyInfo[0] == 'order_id') {
        		$this->handleOrder($bodyInfo[1],1,$response['trade_no']);	
        	}
        	// 充值订单
        	else if ($bodyInfo[0] == 'userId') {
        		$this->handleRechargeOrder($bodyInfo[1],1,$response['trade_no'],$response['total_fee']);
        	}
          
        }

    }

    //充值回调处理 pay_type 1支付宝，2微信  third_trade_no 第三方交易流水号
    pubLic function handleRechargeOrder($user_id,$pay_type,$third_trade_no,$total_fee){
    	$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		// 判断是否已经充值
		$recordInfo = $db->name('money_record')->where(array('third_trade_no'=>$third_trade_no))->find();

		if (isset($recordInfo)) {
			// dump('充值过了');
			echo 'success';
			return;
		}

		$user = $db->name('users')->where(array('userId' => $user_id))->find();

		$recordData = array();
		// 充值
		$recordData['type'] = 3;
		$recordData['money'] = $total_fee;
		$recordData['time'] = time();
		$recordData['orderNo'] = 'CZ'.time();
		$recordData['IncDec'] = 1;
		$recordData['userid'] = $user_id;
		$recordData['remark'] = '支付宝充值';
		$recordData['third_trade_no'] = $third_trade_no;
		$recordData['balance'] = $user['userMoney']+$total_fee;
		// 支付方式
		$recordData['payWay'] = $pay_type;
		$A = $db->name('money_record')->insert($recordData);
		$B= $db->name('users')->where(array('userId' => $user_id))->setInc('userMoney',$total_fee);

		if ($A !==false && $B !==false) {
			echo 'success';return;
		}else{
			echo 'FAIL';return;
		}

    }

    //支付宝支付回调 本地调试使用【需求单】
    public  function aliPayNotify2(){
    
    	$response = json_decode('{"token":"A6068786459797","discount":"0.00","payment_type":"1","trade_no":"2018012821001004590291127253","subject":"\u5e2e\u6211\u9001\u8ba2\u5355","buyer_email":"158****4918","gmt_create":"2018-01-28 18:19:24","notify_type":"trade_status_sync","quantity":"1","out_trade_no":"1517134756122","seller_id":"2088921314486730","notify_time":"2018-01-28 18:19:25","body":"order_id,62","trade_status":"TRADE_SUCCESS","is_total_fee_adjust":"N","total_fee":"0.01","gmt_payment":"2018-01-28 18:19:24","seller_email":"sanzhixiaoji01@163.com","price":"0.01","buyer_id":"2088312885327593","notify_id":"dd673996379cd6c8d30f545df03115akjy","use_coupon":"N","sign_type":"RSA","sign":"UykLmDYCNW8YFFILGP22GkwLTxpNEVbivuickCJLHBhSrK8797PeYcQr1gngLnk1M6qKNoe6kbzmcCMFOVgXrEw2uv9SI1kiXtG8cnhnWSk3VthemBVFGb\/Hod4b1Q8fEbU+SuD5EJ3Wfn6eK5x2ahZGjerDfF+hxVs9wmpNWxU="}', true);
    	// dump($response);
    	// exit();
        if ($response['trade_status'] == 'TRADE_SUCCESS'){
        	$body = $response['body'];
        	// dump($body);
        	$bodyInfo = explode(',',$body);
       		// dump($bodyInfo);
       		// exit();
        	$this->handleOrder($bodyInfo[1],1,$response['trade_no']);
          
        }
 
    }
     //支付宝支付回调 本地调试使用【充值单】
    public  function aliPayNotify3(){
    
    	$response = json_decode('{"token":"A6068786459797","discount":"0.00","payment_type":"1","trade_no":"2018021321001004590232745457","subject":"\u4e09\u53ea\u5c0f\u9e21\u7528\u6237\u4f59\u989d\u5145\u503c","buyer_email":"158****4918","gmt_create":"2018-02-13 09:54:24","notify_type":"trade_status_sync","quantity":"1","out_trade_no":"1518486845146","seller_id":"2088921314486730","notify_time":"2018-02-13 09:54:24","body":"userId,61","trade_status":"TRADE_SUCCESS","is_total_fee_adjust":"N","total_fee":"0.01","gmt_payment":"2018-02-13 09:54:24","seller_email":"sanzhixiaoji01@163.com","price":"0.01","buyer_id":"2088312885327593","notify_id":"ea6b0af293be92f6aeea9cdbae794a8kjy","use_coupon":"N","sign_type":"RSA","sign":"HKu0S7wbXW95Io4+ybh1jDKF1u5eAU7GcKDMdCc3A6h3opvoDIj6\/+jtRbcCYNmhteXyveMvt4zzY7HDILFJ5lumRXgzHEUpU84iw2xMCoJaA9XFAf9HrPGMBo3mGk6lEa++gNlDGrSMxd3mPcPw3Nk82VVFnZuKiVRB6g6Qorw="}', true);
    	// dump($response);
    	// exit();
        if ($response['trade_status'] == 'TRADE_SUCCESS'){
        	$body = $response['body'];
        	// dump($body);
        	$bodyInfo = explode(',',$body);
       		// dump($bodyInfo);
       		// exit();
        	// $this->handleOrder($bodyInfo[1],1,$response['trade_no']);
        	if ($bodyInfo[0] == 'userId') {
        		// dump('前往充值');
        		// exit();
        		$this->handleRechargeOrder($bodyInfo[1],1,$response['trade_no'],$response['total_fee']);
        	}
          
        }
 
    }


    // 处理订单  pay_type 1支付宝，2微信  third_trade_no 第三方交易流水号
    public function handleOrder($order_id,$pay_type,$third_trade_no){
    	// 订单信息
		$send_order_info = db('send_order')->where(array('id'=>$order_id))->find();

		$user_id = $send_order_info['uid'];
		$payWay = $pay_type;

		// 获取用户信息
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$user = $db->name('users')->where(array('userId' => $user_id))->find();
		// 同步回调如果 异步支付已经修改状态直接返回支付成功 只有是未支付状态 才继续
		if ($send_order_info['pay_status'] != 0) {
			echo 'success';return;
		}

		// 生成支付记录
		$db_config = config('database.db_config');
		$db = \Think\Db::connect($db_config);
		$recordData = array();
		// 跑腿单
		$recordData['type'] = 6;
		$recordData['money'] = $send_order_info['money'];
		$recordData['time'] = time();
		$recordData['orderNo'] = $order_id;
		$recordData['IncDec'] = 0;
		$recordData['userid'] = $user_id;
		$recordData['remark'] = '消费';
		$recordData['third_trade_no'] = $third_trade_no;
		$recordData['balance'] = $user['userMoney'];
		// 支付方式
		$recordData['payWay'] = $payWay;
		$db->name('money_record')->insert($recordData);

		// 修改订单状态
		$rs = db('send_order')->where(array('id' => $order_id))->setField('pay_status',1);
		if ($rs !==false) {
			echo 'success';return;
		}else{
			echo 'FAIL';return;
		}

    }

    /**
     * add by hfc 5.15 
     * @param string $url
     * @return mixed
     */
    public function doGet($lat,$lng)
    {
    	$url = "http://api.map.baidu.com/geoconv/v1/?coords=".$lng.",".$lat."&from=3&to=5&ak=".$this->ak;
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
       	$arr = json_decode($output,true);
       	if($arr['status']==0){
       		$data['lat'] = $arr['result'][0]['y'];
       		$data['lng'] = $arr['result'][0]['x'];
       	}else{
       		$data['lat'] = $lat;
       		$data['lng'] = $lng;
       	}
        return $data;
    }
	
}